package com.ccc.boot.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 数据库日志执行类，使用阻塞队列进行异步执行
 *
 * @author superC
 * @version 0.1.0
 * @date 2022/4/8
 */

public class DBLog extends Thread {

    protected static final Logger logger = LoggerFactory.getLogger(DBLog.class);

    private static volatile DBLog dblog = null;

    /**
     * 构建阻塞队列
     */
    private static BlockingQueue<LogInfo> logInfoQueue = new LinkedBlockingQueue<>(1024);

    private ILogService logService;

    public ILogService getLogService() {
        return logService;
    }

    public DBLog setLogService(ILogService logService) {
        this.logService = logService;
        return this;
    }

    /**
     * 懒加载单例模式
     *
     * @return
     */
    public static DBLog getInstance() {
        if (dblog == null) {
            synchronized (DBLog.class) {
                if (dblog == null) {
                    dblog = new DBLog();
                }
            }
        }
        return dblog;
    }

    /**
     * 私有无参构造方法，禁止new对象
     */
    private DBLog() {
        super("CLogOracleWriterThread");
    }

    /**
     * 向队列插入元素
     *
     * @param logInfo
     * @date 2022/4/8 16:19
     * @author superC
     */
    public void offerQueue(LogInfo logInfo) {
        try {
            logInfoQueue.offer(logInfo);
        } catch (Exception e) {
            logger.error("【日志写入异常】\r\n异常记录：", e);
        }
    }

    /**
     *
     *
     * @date 2022/4/8 16:26
     * @author superC
     */
    @Override
    public void run() {
        // 缓冲队列
        List<LogInfo> bufferedLogList = new ArrayList<>();
        while (true) {
            logger.info("run");
            try {
                bufferedLogList.add(logInfoQueue.take());
                logInfoQueue.drainTo(bufferedLogList);
                if (bufferedLogList != null && bufferedLogList.size() > 0) {
                    // 写入日志
                    for (LogInfo log1 : bufferedLogList) {
                        logService.saveLog(log1);
                        logger.info("写入日志成功");
                    }
                }
            } catch (Exception e) {
                logger.error("【日志写入异常】\r\n异常记录：", e);
                // 防止缓冲队列填充数据出现异常时不断刷屏
                try {
                    Thread.sleep(1000);
                } catch (Exception eee) {
                    logger.error("【日志写入异常】\r\n异常记录：", e);
                }
            } finally {
                if (bufferedLogList != null && bufferedLogList.size() > 0) {
                    try {
                        bufferedLogList.clear();
                    } catch (Exception e) {
                        logger.error("【日志写入异常】\r\n异常记录：", e);
                    }
                }
            }
        }
    }
}